package org.example

import org.apache.spark.SparkConf
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}

object Streaming_1 {
  def main(args: Array[String]): Unit = {
    val sparkConf = new SparkConf().setMaster("local[2]").setAppName("NetworkWordCount")
    val ssc = new StreamingContext(sparkConf, Seconds(5))
    ssc.checkpoint("checkpoint_dir")
    val dStream: ReceiverInputDStream[String] = ssc.socketTextStream("172.16.104.7", 9999)
    val lines: DStream[String] = dStream.flatMap(_.split(" "))
    val wordCounts = lines.map(word => (word, 1))
    val updateFunc = (values: Seq[Int], state: Option[Int]) => {
      val currentCount = values.sum
      val previousCount = state.getOrElse(0)
      Some(currentCount + previousCount)
    }
    val runningCounts = wordCounts.updateStateByKey(updateFunc)
    runningCounts.print()
    ssc.start()
    ssc.awaitTermination()


  }

}
